<?php
date_default_timezone_set("PRC");
set_time_limit(0);

include_once (dirname(__FILE__).'/config/database.php');
include_once (dirname(__FILE__).'/class/Log.inc');
include_once (dirname(__FILE__).'/class/Mysql/Exception.inc');
include_once (dirname(__FILE__).'/class/Mysql.inc');


define('LOCK_FILE', dirname(__FILE__).'/lock/createCardDaemon.lock');
define('LOG_LEVEL', 'DEBUG');

$LogFile = dirname(__FILE__).'/log/createCardDaemon'.date('Y.m.d').'.log';

$Log = new Zw_Log();
$Log->setCurrLogLevel(LOG_LEVEL);
$Log->setLogFile($LogFile);

$handle = fopen(LOCK_FILE, 'w+');
if(!flock($handle, LOCK_EX|LOCK_NB)){
	$Log->write('进程已经启动，请不要重复启动');
	exit();
}

$GmDb = new Zw_Mysql();
$GmDb->setLog($Log);
$GmDb->connect($gmDatabaseHost, $gmDatabaseUsername, $gmDatabasePassword, $gmDatabaseName);

while(1)
{
	$LogFile = dirname(__FILE__).'/log/createCardDaemon'.date('Y.m.d').'.log';
	$Log->setLogFile($LogFile);
	
	$sql = "
		select
			`id`,
			`count`,
			`cardId`
		from
			`t_data_card_apply`
		where
			`status` = 2
		limit
			1
	";
	
	if(!(($row = $GmDb->getRow($sql)) === false)){
		$cardApplyId = $row['id'];
		$cardNum = $row['count'];
		$cardId = $row['cardId'];
		$cardSerialArray = array();
		
		unset($row);
		
		$Log->write("开始处理{$cardApplyId}号申请", 'DEBUG');
		$Log->write("卡片数量：{$cardNum}", 'DEBUG');
		
		$sql = "
			delete from
				`t_data_serial`
			where
				`applyId` = '{$cardApplyId}'
		";
		$GmDb->query($sql);
		
		for($i = 0 ; $i < $cardNum ; $i++)
		{
			while(1){
			    $cardSerial = genCardSerial();
				$sql = "
					select
						count(*)
					from
						`t_data_serial`
					where
						`cardSerial` = '{$cardSerial}'
				";
				if($GmDb->getColumn($sql) === '0'){
					$cardSerialArray[] = $cardSerial;
					break;
				}
			}
		}
		
		foreach ($cardSerialArray as $cardSerial){
			$sql = "
				insert into
					`t_data_serial`
				(
					`cardSerial`,
					`applyId`,
					`status`
				)
				value
				(
					'{$cardSerial}',
					'{$cardApplyId}',
					'1'
				)
			";
			$GmDb->query($sql);
		}
		
		$sql = "
			update
				`t_data_card_apply`
			set
				`status` = '4'
			where
				`id` = '{$cardApplyId}'
			";
		
		$GmDb->query($sql);
	}
	
	sleep(5);
}




function genCardSerial($cardSerialLength = 18){
	$cardSerial = '';
//	$cardSerialLength = 18;
	$baseString = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	
	for($i = 0 ; $i < $cardSerialLength ; $i++){
		$cardSerial .= substr($baseString, rand(0, strlen($baseString)-1), 1);
	}
	
	return $cardSerial;
}